package com.app.application;

import java.io.File;
import java.util.ArrayList;

import android.Manifest;
import android.app.AlarmManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.app.config.AppConfig;
import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.DBHelper;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.bugtags.library.Bugtags;
import com.bugtags.library.BugtagsOptions;
import com.core.lib.core.ApiClient;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.controller.base.BaseFragmentActivityChat;
import com.lepu.app.fun.my.bean.BeanCollectKnowledge;
import com.lepu.app.fun.tool.jqtx.util.ToolJqtxUtil;
import com.lepu.app.fun.tool.ymsjb.remind.Alarm;
import com.lepu.app.main.bean.BeanAd;
import com.lepu.app.main.push.PushUtils;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import org.jivesoftware.smack.SmackAndroid;

public class MyApplication extends Application {

	private static final int REQUEST_PERMISSION = 0;

	private static MyApplication mInstance = null;
	public String mBaiduUserId = "";
	public String mBaiduChannelId = "";
	public String mGeTuiChannelId = "";
	public boolean mPushGetSuccessBaidu = false;
	public boolean mPushGetSuccessGeTui = false;

	private Handler chatMsgHandler; // xmpp 消息通知
	private Handler chatSessionHandler; // xmpp chatSession
	private LoginInfo mLoginInfo = null;
	private BaseFragmentActivityChat currentActivity;
	private boolean normalLoginout = true;// 正常退出

	public static AlarmManager alarmManager;
	public ArrayList<BeanAd> mAdList;
	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;

		init();
	}

	private void init() {
		//imageloader
		initImageLoader(this);
		// smark
		SmackAndroid.init(this);
		//bugtags
		//initBugTags();

		UmengHelper.openActivityDurationTrack();
		UmengHelper.updateOnlineConfig(this);
		UmengHelper.EnableEncrypt(true);
		UmengHelper.setDebug(Setting.UmengDebug);// umengFlag

		UtilityBase.DEBUG = Setting.NeedCustomLog;

		//=======================================================================================
		// update login info
		String value = UserConfig.getConfigString(getApplicationContext(),
				Const.CONFIG_APP_LOGIN_INFO, "");
		LogUtilBase.LogD(null, "user_info==" + value);

		LoginInfo loginInfo = LoginInfo.parseLoginInfo(value);
		setLoginInfo(loginInfo);

		// 初始化，检查数据库
		DBHelper.checkDatabase(this);
		
		checkIfDb();
		
		//启动AppService
		//AppService.startAppService(this);
		
		alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
		
		//设置最近的闹钟
	    Alarm.setRemindNextAlarm(this);
	    
	    //设置经期提醒的闹钟
	    ToolJqtxUtil.getInstance(this).setJqtxRemind(false, 0);

		clean();

		//获取广告列表
		MyNetUtil.getInstance().requestGetAd();
	}

	private void clean()
	{
		boolean appFirstUse = AppConfig.getConfigBoolean(this,
				Const.CONFIG_APP_FIRST_USE, true);
		if(appFirstUse)
		{
			Utils.cleanAllFile(this);
		}else{
			//定时清理缓存
			Utils.cleanByTime(this);
		}
	}

	public static MyApplication getInstance() {
		return mInstance;
	}

	public LoginInfo getLoginInfo() {
		return mLoginInfo;
	}

	public void setLoginInfo(LoginInfo loginInfo) {
		if (loginInfo == null) {
			this.mLoginInfo = new LoginInfo();
		} else {
			this.mLoginInfo = loginInfo;
		}
	}

	public boolean checkIsLogin() {

		return LoginUtil.checkIsLogin();
	}

	public boolean checkIsBirthday() {
		boolean flag = false;

		if (mLoginInfo != null && !TextUtils.isEmpty(mLoginInfo.BabyBirthDate)
				&& mLoginInfo.BabyBirthed.equals("1")) {
			flag = true;
		}

		return flag;
	}

	/*
	 * 检查生产方式
	 */
	public boolean checkIsBirthWay() {
		boolean flag = false;

		if (mLoginInfo != null && !TextUtils.isEmpty(mLoginInfo.BirthWay)) {
			flag = true;
		}

		return flag;
	}

	@SuppressWarnings("deprecation")
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.

		String path = SdLocal.getTempFolder(context);
		File cacheDir = new File(path);

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				.memoryCacheExtraOptions(480, 800)
				// default = device screen dimensions
				.discCacheExtraOptions(480, 800, null)
				.threadPoolSize(3)
				// default
				.threadPriority(Thread.NORM_PRIORITY - 1)
				// default
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// default
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(100 * 1024 * 1024))
				.memoryCacheSize(100 * 1024 * 1024).memoryCacheSizePercentage(13) // default
				.discCache(new UnlimitedDiskCache(cacheDir))// default
				.discCacheSize(1000 * 10 * 1024 * 1024) // 缓冲大小
				// .discCacheFileCount(100) // 缓冲文件数目
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
				.imageDecoder(new BaseImageDecoder(false)) // default
				.imageDownloader(
						new BaseImageDownloader(context, 10 * 1000, 30 * 1000)) // connectTimeout
																				// (5
																				// s),
																				// readTimeout
																				// (20
																				// s)
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
				.writeDebugLogs().build();

		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	public Handler getChatSessionHandler() {
		return chatSessionHandler;
	}

	public void setChatSessionHandler(Handler chatSessionHandler) {
		this.chatSessionHandler = chatSessionHandler;
	}

	public Handler getChatMsgHandler() {
		return chatMsgHandler;
	}

	public void setChatMsgHandler(Handler chatMsgHandler) {
		this.chatMsgHandler = chatMsgHandler;
	}

	public BaseFragmentActivityChat getCurrentActivity() {
		return currentActivity;
	}

	public void setCurrentActivity(BaseFragmentActivityChat currentActivity) {
		this.currentActivity = currentActivity;
	}

	public boolean isNormalLoginout() {
		return normalLoginout;
	}

	public void setNormalLoginout(boolean normalLoginout) {
		this.normalLoginout = normalLoginout;
	}

	private void initBugTags()
	{
		//初始化Bugtags
		try {
			BugtagsOptions options = new BugtagsOptions.Builder().
					trackingLocation(true).//是否获取位置，默认 true
					trackingCrashLog(true).//是否收集crash，默认 true
					trackingConsoleLog(true).//是否收集console log，默认 true
					trackingUserSteps(true).//是否收集用户操作步骤，默认 true
					build();
			int btgValue = Bugtags.BTGInvocationEventBubble;
			if(!Setting.DEBUG){
				btgValue = Bugtags.BTGInvocationEventNone;
			}
			Bugtags.start("57f1fa174e0bd9dd180e17e849d80cee", this,
					btgValue, options);
		}catch (Exception e){

		}
	}

	/**
	 * 这个方法已不使用
	 */
	private void checkIfDb() {
		DBHelper dbHelper = DBHelper.getInstance(DBHelper.DATABASE_NAME_ALBUM);
		if (dbHelper != null) {
			boolean flag1 = dbHelper.isColumeExists("CollectHistory",
					"ArticleID");
			LogUtilBase.LogD(null, "CollectHistory ===========>" + flag1);
			if (!flag1) {
				String sql1 = "alter table CollectHistory add column Title TEXT";
				String sql2 = "alter table CollectHistory add column SubTitle TEXT";
				String sql3 = "alter table CollectHistory add column ArticleID TEXT";

				dbHelper.executeNonQuery(sql1, new Object[] {});
				dbHelper.executeNonQuery(sql2, new Object[] {});
				dbHelper.executeNonQuery(sql3, new Object[] {});
			}

			// 是否有MyMessage表
			boolean flag2 = dbHelper.isTableExists("MyMessage");
			LogUtilBase.LogD(null, "MyMessage ===========>" + flag2);
			if (!flag2) {
				String sql = getString(R.string.create_table_my_message);
				dbHelper.executeNonQuery(sql, new Object[] {});
			}

			// 是否有chat_session表
			boolean flag3 = dbHelper.isTableExists("chat_Message");
			LogUtilBase.LogD(null, "chat_Message ===========>" + flag2);
			if (!flag3) {
				String sql = getString(R.string.create_table_chat_message);
				dbHelper.executeNonQuery(sql, new Object[] {});
				String sql2 = getString(R.string.create_table_chat_session);
				dbHelper.executeNonQuery(sql2, new Object[] {});
				String sql3 = getString(R.string.create_table_doctor);
				dbHelper.executeNonQuery(sql3, new Object[] {});
			}

			//删除旧版本视频,文章数据。db version 6
			BeanCollectKnowledge.deleteCollectData(BeanCollectKnowledge.TYPE_VIDEO_OLD);
			BeanCollectKnowledge.deleteCollectData(BeanCollectKnowledge.TYPE_ARTICLE_OLD);

			//
			// 是否有ToolTaiErNew表
			DBHelper dbHelpTool = DBHelper.getInstance(DBHelper.DATABASE_NAME_TOOL);
			boolean flagToolTaiErNew = dbHelpTool.isTableExists("ToolTaiErNew");
			LogUtilBase.LogD(null, "ToolTaiErNew ===========>" + flagToolTaiErNew);
			if (!flagToolTaiErNew) {
				String sql = getString(R.string.create_table_ToolTaiErNew);
				dbHelpTool.executeNonQuery(sql, new Object[] {});

				String sql2 = getString(R.string.create_table_ToolTaiErNew_data);
				String[] dataArray = sql2.split(";");
				for(int i=0;i<dataArray.length;i++){
					dbHelpTool.executeNonQuery(dataArray[i], new Object[] {});
				}
			}
		}
	}
}
